<?php defined('BASEPATH') OR exit('No direct script access allowed');

class User extends Services{
	private $status = true;
	
	function User(){
		parent::__construct();
	}
	
	/**
	 * Servicio de login de usuario.
	 */
	protected function login_user(){
		$this->checkConsumerKey();
		
		$response_errors = $this->validate('login');
		if($this->status == true){
			$this->load->model('user_model');
			$res_save = $this->user_model->login(self::$params);
			if(is_array($res_save))
				return $this->parseOutput($res_save);
			else 
				throw new UserNotFoundException();
		}else
			throw new UserValidateException(implode(',',$response_errors));
	}
	
	
	/**
	 * Servicio de registro de usuario.
	 */
	protected function register(){
		$response_errors = $this->validate('register');
		if($this->status == true){
			$this->load->model('user_model');
			$res_save = $this->user_model->saveInfoUser(self::$params);
			if($res_save==false)
				throw new UserAlreadyExistsException();
			else{
				$url = $this->config->item('base_url').'services/oauth/register_user?consumer_key='.
						Sys::$consumer_key.'&user_id='.$res_save.
						'&consumer_secret='.Sys::$consumer_secret;
				header("Location: ".$url);
				exit;
			}
			//return $this->parseOutput(array("user_id" => $res_save));
		}else
			throw new UserValidateException(implode(',',$response_errors));
	}
	
	/**
	 * Servicio que obtiene la informacion base del usuario que coincida con el 
	 * oauth_token y el consumer_key
	 */
	protected function query(){
		$this->checkAccessToken();
		
		$this->load->model('user_model');
		$data = $this->user_model->getInfoUser(self::$params);
		
		return $this->parseOutput($data);
	}
	
	/**
	 * Servicio que actualiza la información base del usuario que coincida con el 
	 * oauth_token y el consumer_key
	 */
	public function edit(){
		$this->checkAccessToken();
		
		$response_errors = $this->validate('edit');
		if($this->status == true){
			$this->load->model('user_model');
			
			$resp = $this->user_model->updateInfoUser(self::$params);
			if($resp==FALSE)
				throw new UserNotFoundException();
			else
				return $this->parseOutput(array('user_id' => $resp));
		}else{
			throw new UserValidateException(implode(',',$response_errors));
		}
	}
	
	
	
	
	
	/**
     * Permite incorporar las validaciones bases que apliquen para todos los servicios.
     * Validaciones mas espesificas tendran que ser en cada servicio en particular.
     * @author gama
     */
    private function validate($val_method){
    	if(method_exists($this, 'validate_'.$val_method)){
    		$this->load->library('MY_Form_validation');
    		return $this->{'validate_'.$val_method}();
    	}
    }
    
	private function validate_login(){
    	$validate = new MY_Form_validation();
    	$validate->setArrayValidate(self::$params);
    	
    	$validate->set_rules(array(
    			array('field' => 'email', 
                     'label' => 'email', 
                     'rules' => 'required|valid_email'),
    			array('field' => 'password', 
                     'label' => 'password', 
                     'rules' => 'required|max_length[32]')
    	));
    	$this->status = $validate->run();
    	return $validate->_error_array;
    }
    
    private function validate_edit(){
    $validate = new MY_Form_validation();
    	$validate->setArrayValidate(self::$params);
    	
    	$validate->set_rules(array(
    			array('field' => 'name', 
                     'label' => 'name', 
                     'rules' => 'max_length[50]'),
    			array('field' => 'email', 
                     'label' => 'email', 
                     'rules' => 'valid_email|max_length[70]'),
    			array('field' => 'password', 
                     'label' => 'password', 
                     'rules' => 'min_length[6]|max_length[32]'),
    			array('field' => 'confirm_password', 
                     'label' => 'confirm_password', 
                     'rules' => 'max_length[32]'),
                     
				array('field' => 'user', 
                     'label' => 'user', 
                     'rules' => 'max_length[15]')
    	));
    	$this->status = $validate->run();
    	
    	if(isset(self::$params["confirm_password"])){
    		if(self::$params["confirm_password"] != self::$params["password"]){
    			$this->status = false;
    			$validate->_error_array['values'] = lang('txt_password_confirm');
    		}
    	}
    	
    	return $validate->_error_array;
    }
    
    private function validate_register(){
    	$validate = new MY_Form_validation();
    	$validate->setArrayValidate(self::$params);
    	
    	$validate->set_rules(array(
    			array('field' => 'name', 
                     'label' => 'name', 
                     'rules' => 'required|max_length[50]'),
    			array('field' => 'email', 
                     'label' => 'email', 
                     'rules' => 'required|valid_email|max_length[70]'),
    			array('field' => 'password', 
                     'label' => 'password', 
                     'rules' => 'required|min_length[6]|max_length[32]'),
    			array('field' => 'confirm_password', 
                     'label' => 'confirm_password', 
                     'rules' => 'max_length[32]'),
                     
				array('field' => 'user', 
                     'label' => 'user', 
                     'rules' => 'max_length[15]')
    	));
    	$this->status = $validate->run();
    	
    	if(isset(self::$params["confirm_password"])){
    		if(self::$params["confirm_password"] != self::$params["password"]){
    			$this->status = false;
    			$validate->_error_array['values'] = lang('txt_password_confirm');
    		}
    	}
    	
    	return $validate->_error_array;
    }
    
	
	
    
    
    
	/**
	 * 
	 * Para el acceso a los datos
	 */
	protected function login(){
		$this->checkConsumerKey();
		
		$response_errors = $this->validate('login');
		if($this->status == true){
			$this->load->model('user_model');
			self::$params['password'] = md5(self::$params['password']);
			$res_save = $this->user_model->login(self::$params);
			if(is_array($res_save)){
				self::$params["token"] = $res_save["token"];
				self::$params["usr_id"] = $res_save["user_id"];
				$this->sigin();
				return $this->parseOutput($res_save);
			}else 
				throw new UserNotFoundException();
		}else
			throw new UserValidateException(implode(',',$response_errors));
	}
	
	protected function logout(){
		$lang = isset(self::$params['lang_url'])? (self::$params['lang_url']!=''? self::$params['lang_url'].'/': ''): '';
		setcookie('p_usr_id', '', time()-(3600*24*Sys::$destroy_session), '/');
		setcookie('p_usr_token', '', time()-(3600*24*Sys::$destroy_session), '/');
		header("Location: ".$this->config->item('base_url').$lang);
	}
	
	protected function sigin(){
		if(isset(self::$params['usr_id'])){
			setcookie('p_usr_id', self::$params['usr_id'], time()+(3600*24*Sys::$destroy_session), '/');
		}
		if(isset(self::$params['token'])){
			setcookie('p_usr_token', self::$params['token'], time()+(3600*24*Sys::$destroy_session), '/');
		}
		setcookie('p_lang', Sys::getLang(), time()+(3600*24*Sys::$destroy_session*20), '/');
		
		//redirecciona si es el login de la pag
		if(isset(self::$params['is_login'])){
			header('Location: '.$this->config->item('base_url'));
			exit;
		}
	}
	
	
	private function parseOutput($data=array(), $only_parse=false){
		if ($only_parse)
			return $this->{'_format_'.$this->getFormat()}($data);
		if($this->status==true){
			return $this->{'_trim_format_'.$this->getFormat()}(
					$this->{'_format_'.$this->getFormat()}($data)
					);
		}
    }
}